import importlib
import os
import sys
import time
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
from workflow import *

def get_module_name(src_path, workflow_dir):
    try:
        relative_path = os.path.relpath(src_path, workflow_dir)
    except ValueError:
        return None
    module_path, ext = os.path.splitext(relative_path)
    if ext != '.py':
        return None
    module_path = module_path.replace(os.path.sep, '.')
    if module_path.endswith('.__init__'):
        module_path = module_path[:-9]
    if module_path == '__init__':
        module_name = 'workflow'
    else:
        module_name = f'workflow.{module_path}' if module_path else 'workflow'
    return module_name

class ReloadHandler(FileSystemEventHandler):
    def __init__(self, workflow_dir):
        super().__init__()
        self.workflow_dir = workflow_dir
        self.last_processed = {}

    def on_modified(self, event):
        if not event.is_directory:
            self._process_event(event)

    def on_created(self, event):
        if not event.is_directory:
            self._process_event(event)

    def _process_event(self, event):
        src_path = event.src_path
        current_time = time.time()
        if src_path in self.last_processed:
            if current_time - self.last_processed[src_path] < 0.5:
                return
        self.last_processed[src_path] = current_time

        module_name = get_module_name(src_path, self.workflow_dir)
        if not module_name:
            return

        print(f"Attempting to reload module: {module_name}")
        try:
            if module_name in sys.modules:
                module = sys.modules[module_name]
            else:
                module = importlib.import_module(module_name)
            importlib.reload(module)
            print(f"Successfully reloaded module: {module_name}")
        except Exception as e:
            print(f"Error reloading module {module_name}: {e}")

# def main():
#     workflow_dir = os.path.abspath('workflow')
#     project_dir = os.path.dirname(workflow_dir)
#     if project_dir not in sys.path:
#         sys.path.insert(0, project_dir)

#     # 确保workflow是一个包
#     init_py = os.path.join(workflow_dir, '__init__.py')
#     if not os.path.exists(init_py):
#         open(init_py, 'a').close()

#     event_handler = ReloadHandler(workflow_dir)
#     observer = Observer()
#     observer.schedule(event_handler, workflow_dir, recursive=True)
#     observer.start()

#     try:
#         while True:
#             a.func1()
#             time.sleep(2)
#     except KeyboardInterrupt:
#         observer.stop()
#     observer.join()

# if __name__ == '__main__':
#     main()